var userInfo;
var homeHash = "views/index/main";
$(function () {
    layui.config({
        base: context + '/res/module/'
    }).extend({
        treeTable: 'treeTable/treeTable',
        treetable: 'treetable-lay/treetable',
        tableSelect: 'tableSelect'
    });
    layui.use(['layer', 'upload', 'element', 'form'], function () {
        var layer = layui.layer;
        let upload = layui.upload;
        checkLoginStatus();
        //getLeftMenu();
        //点击修改密码
        $('#changePassword').click(function () {
            var passIndex = layer.open({
                type: 1,
                title: '密码修改',
                content: $("#edit_pwd"),
                area: ['400px', '300px'],
                shade: 0.6, //遮罩透明度
                anim: 1, //0-6的动画形式，-1不开启
                btn: ['确认修改', '取消'],
                yes: function () {
                    var nowpassword = $('#nowpassword').val();
                    var password = $('#password').val();
                    var repassword = $('#repassword').val();
                    if (nowpassword == '') {
                        layer.msg('请输入初始密码');
                    } else if (password == '') {
                        layer.msg('请输入新密码');
                    } else if (repassword == '') {
                        layer.msg('请确认新密码');
                    } else if (password != repassword) {
                        layer.msg('两次密码不一致');
                    } else {
                        var jsonData = {
                            password: nowpassword,
                            newPassword: repassword
                        };
                        $.ajax({
                            url: context + '/api/sysuser/changepassword',
                            type: 'PATCH',
                            async: false,
                            dataType: 'json',
                            contentType: "application/json;charset-UTF-8",
                            data: JSON.stringify(jsonData),
                            success: function (result) {
                                if (result.success) {
                                    layer.msg('修改密码成功3s后自动跳转到登录页');
                                    localStorage.clear('password');
                                    setTimeout(function () {
                                        window.location.href = 'views/login.html';
                                    }, 3000)

                                } else {
                                    layer.msg(result.msg);
                                }
                            },
                            error: function () {
                                layer.msg("操作异常");
                            }
                        });
                    }
                },
                end: function () {
                    $('#nowpassword').val('');
                    $('#password').val('');
                    $('#repassword').val('');
                },
            })
        });

        $(document).on("click", "a[data-url]", function (e) {
            var hash = e.target.getAttribute("data-url");
            jump(hash);
        });

        //刷新
        location.hash = "";
        jump("./views/index/main");


//弹出上传文件选择框, id为点击事件源,imgUrl为提交表单元素,img为img标签显示图片
        _uploadFile = function(param){
            param = param || {};
            let uploadInst = upload.render({
                elem: '#' + (param.id || "upload_header")
                , url: context + '/api/fileupload/add'
                , field: 'attach'
                , done: function (res) {
                    if(typeof param.done == 'function'){
                        param.done(res);
                    }else{
                        if (res.success) {
                            $('#' + (param.imgUrl || "imgUrl")).val(res.link);
                            $('#' + (param.img || "img")).attr('src', res.link);
                            param.href && $('#' + (param.href)).attr('href', res.link);
                        } else {
                            layui.layer.msg('上传失败');
                        }
                    }
                }
                , error: function () {
                    //演示失败状态，并实现重传
                    // let demoText = $('#demoText');
                    // demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                    // demoText.find('.demo-reload').on('click', function () {uploadInst.upload();});
                }
            });
        }
        //获取当前公众号及其他公众号
        //getCountStatus();

        // var _hmt=_hmt||[];(function(){var hm=document.createElement("script");hm.src="https://hm.baidu.com/hm.js?f07686635800b1dc0587d91cd81bf3b0";var s=document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm,s)})();
        // (function(){var bp=document.createElement("script");var curProtocol=window.location.protocol.split(":")[0];if(curProtocol==="https"){bp.src="https://zz.bdstatic.com/linksubmit/push.js"}else{bp.src="http://push.zhanzhang.baidu.com/push.js"}var s=document.getElementsByTagName("script")[0];s.parentNode.insertBefore(bp,s)})();
    });
});

function createTableItem(obj) {
    return obj;
}

//检测是否登录
function checkLoginStatus() {
    $.ajax({
        url: context + '/api/sysuser/getuserbysession?flush=true',
        type: 'get',
        success: function (result) {
            if (result.success) {
                userInfo = result.data;
                $('#userPhoto').attr('src', userInfo.photo);
                $('#userName').html(userInfo.nickname);
            } else {
                window.location.href = './views/login.html';
            }
        }
    });
}

function confirmDel(url, table){
    layer.confirm('确认删除？', {
        icon: 7,
        title: "提示",
        btn: ['确认', '取消'] //按钮
    }, function () {
        $.ajax({
            url: url,
            type: "DELETE",
            success: function (result) {
                if (result.success && result.data > 0) {
                    layer.msg("删除成功");
                    //刷新列表
                    table && reloadTable(table);
                } else {
                    layer.msg(result.msg || "删除失败");
                }
            },
            error: function () {
                layer.msg("删除异常");
            }
        })
    }, function () {
        layer.closeAll();
    });
}
function getLeftMenu() {

    $.ajax({
        url: context + '/api/sysuser/menus',
        type: 'get',
        dataType: 'json',
        success: function (data) {
            var menu = ""; //定义变量存储
            var parent = data.menus.menus;
            if (parent.length > 0) {
                for (var i = 0; i < parent.length; i++) {
                    if (parent[i].menu_flag == 'Y') {
                        menu += "<li class='layui-nav-item layui-nav-itemed'>"
                        menu += "<a href='javascript:'>" + parent[i].permissionName + "</a>"
                        //console.log(menu);
                        var childs = parent[i].children;
                        menu += "<dl class='layui-nav-child'>"
                        for (var j = 0; j < childs.length; j++) { //继续遍历这几条数据
                            menu += "<dd>"
                            menu += "<a href='javascript:;'  data-url='" + childs[j].url + "'>" + childs[j].permissionName + "</a>"
                            menu += "</dd>"
                            // console.log(menu);

                        }
                        menu += "</dl>"
                        menu += "</li>";
                    }
                }
                //console.log(menu);
                $("#nav").html(menu);
                var element = layui.element;
                element.init()//初始化element事件，使菜单展开
                var $firstA = $("#index_menu .layui-nav-item:first>a");

                if ($firstA.attr("data-url")) {
                    window.homeHash = $firstA.attr("data-url");
                } else {
                    window.homeHash = $("#index_menu .layui-nav-item:first dd:first>a").data("url");
                }
                //如果由index.html首次进入页面,顶掉页面url历史记录
                var title = document.title;
                var hash = (location.hash == "" || location.hash.length === 1) ? homeHash : location.hash.substring(1);
                var url = location.protocol + '//' + location.host + location.pathname + location.search + '#' + hash;
                history.replaceState(null, title, url);
                // replaceState事件无法手动触发
                hashchange();

                //hash监听，用于回退及点击菜单
                window.addEventListener('hashchange', hashchange, false);
            } else {

                $('#nav').html('<li class="layui-nav-item layui-nav-itemed"><a href="javascript:;" data-url=""><i class="iconfont icon-shouye"></i>用户信息</a></li> ');
            }
        }
    });
}

// 退出
$("#exit").on("click", function () {
    $.ajax({
        url: context + '/api/login/logout',
        type: 'GET',
        async: false,
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location.href = "views/login.html";
            } else {
                layer.msg("退出失败");
            }
        }

    });
});

/**
 * hashchange的回调函数，渲染右侧
 *
 * @author zhaoqf
 */
function hashchange() {
    var hash = (location.hash === "" || location.hash.length === 1) ? homeHash : location.hash.substring(1);
    hash = hash.replace(/\[.*\]/, "");
    // var path="/views/"+hash+".html";
    var path = hash + ".html";
    renderHtml({
        targetId: 'index_right',
        template: path
    });
    var $a = $(".fsh-menu a[data-url='" + hash + "']");
    if ($a.length > 0) {
        $a.parent().addClass('layui-this');
    }
    // if (!$a.parent().hasClass("layui-this")) {
    // $a.parents('li').addClass('layui-nav-itemed').siblings('li').removeClass('layui-nav-itemed');
    // $a.parent("dd").addClass('layui-this').siblings('.layui-this').removeClass('layui-this');
    // }
    layer.closeAll();
}

/**
 * 改变hash方式跳转
 *
 * @author zhaoqf
 */
function jump(hash) {
    if (location.hash !== "#" + hash) {
        location.hash = hash;
        hashchange();
    }
}

function backHashClick() {

}
/**
 * 获取hash中的参数，hash=/aaa/aaa[a=1&b=2]
 *
 * @author zhaoqf
 */
function getHashParam() {
    var hash = location.hash;
    var param = hash.match(/\[(.*)\]/, "");
    if (!param) {
        return {};
    } else {
        var arr = param[1].split("&");
        var o = {};
        for (var i = 0; i < arr.length; i++) {
            var d = arr[i].split("=");
            d.length == 2 && (o[d[0]] = d[1]);
        }
        return o;
    }
}
